<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表格生成与编辑工具</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .toolbar {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        .btn {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .btn-secondary {
            background-color: #2196F3;
        }
        .btn-secondary:hover {
            background-color: #0b7dda;
        }
        .btn-danger {
            background-color: #f44336;
        }
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        .btn-group {
            display: flex;
            gap: 5px;
        }
        .table-container {
            overflow-x: auto;
            margin-bottom: 20px;
        }
        .editable-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }
        .editable-table th, .editable-table td {
            border: 1px solid #ddd;
            padding: 8px;
            position: relative;
        }
        .editable-table th {
            background-color: #f2f2f2;
            font-weight: bold;
            text-align: left;
        }
        .editable-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .editable-table tr:hover {
            background-color: #f1f1f1;
        }
        .cell-editable {
            min-height: 20px;
            min-width: 50px;
            outline: none;
        }
        .add-column, .add-row {
            display: inline-block;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background-color: #4CAF50;
            color: white;
            border-radius: 50%;
            cursor: pointer;
            font-weight: bold;
            margin-left: 5px;
        }
        .add-column {
            position: absolute;
            top: -12px;
            right: -12px;
        }
        .add-row {
            position: absolute;
            bottom: -12px;
            left: -12px;
        }
        .row-actions, .col-actions {
            visibility: hidden;
            position: absolute;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 5px;
            z-index: 100;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .row-actions {
            left: -5px;
            top: 100%;
        }
        .col-actions {
            top: -5px;
            left: 100%;
        }
        .action-btn {
            padding: 3px 8px;
            margin: 2px;
            background-color: #f1f1f1;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        .action-btn:hover {
            background-color: #ddd;
        }
        .delete-btn {
            color: #f44336;
        }
        .paste-area {
            width: 100%;
            height: 100px;
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }
        .instructions {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #e8f5e9;
            border-radius: 4px;
            border-left: 4px solid #4CAF50;
        }
        .instructions h3 {
            margin-top: 0;
            color: #2e7d32;
        }
        .instructions ul {
            margin-bottom: 0;
            padding-left: 20px;
        }
        .message {
            padding: 10px;
            margin-top: 10px;
            border-radius: 4px;
            display: none;
        }
        .message.success {
            background-color: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #a5d6a7;
        }
        .message.error {
            background-color: #ffebee;
            color: #c62828;
            border: 1px solid #ef9a9a;
        }
        .hidden {
            display: none;
        }
        .table-name-container {
            margin-bottom: 15px;
        }
        .table-name-input {
            padding: 8px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .saved-tables {
            margin-top: 20px;
            border-top: 1px solid #ddd;
            padding-top: 20px;
        }
        .saved-tables h3 {
            margin-top: 0;
        }
        .table-list {
            list-style-type: none;
            padding: 0;
        }
        .table-list li {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .table-list li:hover {
            background-color: #f9f9f9;
        }
        .table-actions {
            display: flex;
            gap: 5px;
        }
        .excel-upload-container {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f0f8ff;
            border-radius: 8px;
            border: 1px solid #b3d4fc;
        }
        .excel-upload-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .excel-upload-header h3 {
            margin: 0;
            color: #2196F3;
        }
        .file-input-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        .file-input-container input[type="file"] {
            flex-grow: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .sheet-selector {
            display: none;
            margin-top: 15px;
        }
        .sheet-selector select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
            min-width: 200px;
        }
        .preview-container {
            margin-top: 15px;
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            background-color: white;
        }
        .preview-table {
            width: 100%;
            border-collapse: collapse;
        }
        .preview-table th, .preview-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .preview-table th {
            background-color: #f2f2f2;
        }
        .toggle-container {
            cursor: pointer;
            user-select: none;
            color: #2196F3;
        }
        .toggle-icon {
            display: inline-block;
            transition: transform 0.3s;
        }
        .toggle-icon.open {
            transform: rotate(90deg);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>表格生成与编辑工具</h1>
        
        <div class="instructions">
            <h3>使用说明：</h3>
            <ul>
                <li>可以从Excel直接复制内容，粘贴到下方文本框，然后点击"从Excel粘贴生成表格"</li>
                <li>也可以直接上传Excel文件，选择要导入的表格</li>
                <li>点击单元格可以直接编辑内容</li>
                <li>点击表头或行首的"+"按钮可以添加列或行</li>
                <li>右键点击表头或行可以删除列或行</li>
                <li>表格数据会自动保存到本地，也可以点击"保存表格"手动保存</li>
            </ul>
        </div>
        
        <div class="excel-upload-container">
            <div class="excel-upload-header">
                <h3>从Excel文件导入</h3>
                <div class="toggle-container" onclick="toggleExcelUpload()">
                    <span class="toggle-icon">▶</span> 点击展开/收起
                </div>
            </div>
            
            <div id="excelUploadContent" style="display:none;">
                <div class="file-input-container">
                    <input type="file" id="excelFileInput" accept=".xlsx,.xls">
                    <button class="btn btn-secondary" id="uploadExcelBtn">上传并解析</button>
                </div>
                
                <div id="sheetSelector" class="sheet-selector">
                    <div>
                        <label for="sheetSelect">选择要导入的表格：</label>
                        <select id="sheetSelect" onchange="showSheetPreview()"></select>
                        <button class="btn" id="importSheetBtn">导入选中表格</button>
                    </div>
                    
                    <div id="previewContainer" class="preview-container">
                        <table id="previewTable" class="preview-table">
                            <!-- 预览内容将在这里显示 -->
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="paste-container">
            <textarea class="paste-area" id="pasteArea" placeholder="从Excel复制数据，粘贴到这里..."></textarea>
            <button class="btn" id="generateTableBtn">从Excel粘贴生成表格</button>
            <button class="btn btn-secondary" id="clearPasteBtn">清空粘贴区</button>
        </div>
        
        <div class="table-name-container">
            <input type="text" id="tableNameInput" class="table-name-input" placeholder="表格名称（保存时使用）">
        </div>
        
        <div class="toolbar">
            <div class="btn-group">
                <button class="btn" id="addRowBtn">添加行</button>
                <button class="btn" id="addColBtn">添加列</button>
            </div>
            <button class="btn btn-secondary" id="saveTableBtn">保存表格</button>
            <button class="btn btn-danger" id="clearTableBtn">清空表格</button>
        </div>
        
        <div class="table-container">
            <table class="editable-table" id="editableTable">
                <thead>
                    <tr>
                        <th>列1<span class="add-column" title="添加列">+</span></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td contenteditable="true" class="cell-editable"><span class="add-row" title="添加行">+</span></td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div id="message" class="message"></div>
        
        <div class="saved-tables">
            <h3>已保存的表格</h3>
            <ul class="table-list" id="savedTablesList">
                <!-- 已保存的表格将在这里显示 -->
            </ul>
        </div>
    </div>

    <script>
        // 当前表格数据
        let tableData = [['']];
        let currentTableName = '';
        let savedTables = {};
        
        // DOM元素
        const editableTable = document.getElementById('editableTable');
        const pasteArea = document.getElementById('pasteArea');
        const generateTableBtn = document.getElementById('generateTableBtn');
        const clearPasteBtn = document.getElementById('clearPasteBtn');
        const addRowBtn = document.getElementById('addRowBtn');
        const addColBtn = document.getElementById('addColBtn');
        const saveTableBtn = document.getElementById('saveTableBtn');
        const clearTableBtn = document.getElementById('clearTableBtn');
        const tableNameInput = document.getElementById('tableNameInput');
        const savedTablesList = document.getElementById('savedTablesList');
        const messageEl = document.getElementById('message');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadSavedTables();
            renderSavedTablesList();
            
            // 添加Excel文件上传事件监听
            document.getElementById('uploadExcelBtn').addEventListener('click', uploadExcelFile);
            document.getElementById('importSheetBtn').addEventListener('click', importSelectedSheet);
        });
        
        // 切换Excel上传区域的显示/隐藏
        function toggleExcelUpload() {
            const content = document.getElementById('excelUploadContent');
            const toggleIcon = document.querySelector('.toggle-icon');
            
            if (content.style.display === 'none') {
                content.style.display = 'block';
                toggleIcon.classList.add('open');
            } else {
                content.style.display = 'none';
                toggleIcon.classList.remove('open');
            }
        }
        
        // 上传Excel文件
        function uploadExcelFile() {
            const fileInput = document.getElementById('excelFileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                showMessage('请先选择Excel文件', 'error');
                return;
            }
            
            // 检查文件类型
            if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                showMessage('只支持.xlsx或.xls格式的Excel文件', 'error');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);
            
            // 显示加载中的消息
            showMessage('正在解析Excel文件...', 'success');
            
            // 发送请求
            fetch('/text2html/upload_excel', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.detail || '上传Excel文件失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                // 显示表格选择器
                const sheetSelector = document.getElementById('sheetSelector');
                sheetSelector.style.display = 'block';
                
                // 填充表格选择下拉框
                const sheetSelect = document.getElementById('sheetSelect');
                sheetSelect.innerHTML = '';
                
                data.sheets.forEach(sheet => {
                    const option = document.createElement('option');
                    option.value = sheet;
                    option.textContent = sheet;
                    sheetSelect.appendChild(option);
                });
                
                // 保存预览数据和文件路径
                window.previewData = data.preview_data;
                window.savedFilePath = data.saved_path;
                
                // 显示第一个表格的预览
                if (data.sheets.length > 0) {
                    showSheetPreview();
                }
                
                showMessage(`Excel文件解析成功，包含 ${data.sheets.length} 个表格`, 'success');
            })
            .catch(error => {
                console.error('上传Excel文件错误:', error);
                showMessage('上传Excel文件失败: ' + error.message, 'error');
            });
        }
        
        // 显示表格预览
        function showSheetPreview() {
            const sheetSelect = document.getElementById('sheetSelect');
            const selectedSheet = sheetSelect.value;
            
            if (!selectedSheet || !window.previewData || !window.previewData[selectedSheet]) {
                return;
            }
            
            const previewData = window.previewData[selectedSheet];
            const previewTable = document.getElementById('previewTable');
            
            // 清空预览表格
            previewTable.innerHTML = '';
            
            if (previewData.length === 0) {
                previewTable.innerHTML = '<tr><td>表格为空</td></tr>';
                return;
            }
            
            // 创建表头
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');
            
            Object.keys(previewData[0]).forEach(key => {
                const th = document.createElement('th');
                th.textContent = key;
                headerRow.appendChild(th);
            });
            
            thead.appendChild(headerRow);
            previewTable.appendChild(thead);
            
            // 创建表体
            const tbody = document.createElement('tbody');
            
            previewData.forEach(row => {
                const tr = document.createElement('tr');
                
                Object.values(row).forEach(value => {
                    const td = document.createElement('td');
                    td.textContent = value;
                    tr.appendChild(td);
                });
                
                tbody.appendChild(tr);
            });
            
            previewTable.appendChild(tbody);
        }
        
        // 导入选中的表格
        function importSelectedSheet() {
            const fileInput = document.getElementById('excelFileInput');
            const file = fileInput.files[0];
            const sheetSelect = document.getElementById('sheetSelect');
            const selectedSheet = sheetSelect.value;
            
            if (!file || !selectedSheet) {
                showMessage('请选择Excel文件和表格', 'error');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);
            formData.append('sheet_name', selectedSheet);
            
            // 显示加载中的消息
            showMessage('正在导入表格数据...', 'success');
            
            // 发送请求
            fetch('/text2html/read_excel_sheet', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.detail || '读取表格数据失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                // 更新表格数据
                if (data.headers && data.data) {
                    // 转换数据格式
                    tableData = [data.headers];
                    tableData = tableData.concat(data.data);
                    
                    // 渲染表格
                    renderTable();
                    
                    // 设置表格名称
                    const tableName = `${data.filename.split('.')[0]}_${data.sheet_name}`;
                    document.getElementById('tableNameInput').value = tableName;
                    
                    showMessage(`表格 "${data.sheet_name}" 导入成功`, 'success');
                } else {
                    showMessage('表格数据格式不正确', 'error');
                }
            })
            .catch(error => {
                console.error('导入表格错误:', error);
                showMessage('导入表格失败: ' + error.message, 'error');
            });
        }
        
        // 从Excel粘贴生成表格
        generateTableBtn.addEventListener('click', function() {
            const pasteContent = pasteArea.value.trim();
            if (!pasteContent) {
                showMessage('请先粘贴Excel数据', 'error');
                return;
            }
            
            // 解析粘贴的内容
            const rows = pasteContent.split(/\r?\n/);
            tableData = rows.map(row => row.split('\t'));
            
            // 渲染表格
            renderTable();
            showMessage('表格已生成', 'success');
        });
        
        // 清空粘贴区
        clearPasteBtn.addEventListener('click', function() {
            pasteArea.value = '';
        });
        
        // 添加行
        addRowBtn.addEventListener('click', function() {
            const colCount = tableData[0].length;
            const newRow = Array(colCount).fill('');
            tableData.push(newRow);
            renderTable();
        });
        
        // 添加列
        addColBtn.addEventListener('click', function() {
            tableData.forEach(row => row.push(''));
            renderTable();
        });
        
        // 保存表格
        saveTableBtn.addEventListener('click', function() {
            const tableName = tableNameInput.value.trim();
            if (!tableName) {
                showMessage('请输入表格名称', 'error');
                return;
            }
            
            // 保存表格数据
            currentTableName = tableName;
            savedTables[tableName] = {
                data: tableData,
                timestamp: new Date().toISOString()
            };
            
            // 保存到本地存储
            saveToLocalStorage();
            
            // 更新已保存表格列表
            renderSavedTablesList();
            
            showMessage(`表格 "${tableName}" 已保存`, 'success');
        });
        
        // 清空表格
        clearTableBtn.addEventListener('click', function() {
            if (confirm('确定要清空当前表格吗？')) {
                tableData = [['']];
                renderTable();
                showMessage('表格已清空', 'success');
            }
        });
        
        // 渲染表格
        function renderTable() {
            const thead = document.createElement('thead');
            const tbody = document.createElement('tbody');
            
            // 创建表头
            const headerRow = document.createElement('tr');
            tableData[0].forEach((cell, colIndex) => {
                const th = document.createElement('th');
                th.dataset.col = colIndex;
                th.innerHTML = `
                    <div class="cell-editable" contenteditable="true">${escapeHtml(cell)}</div>
                    ${colIndex === tableData[0].length - 1 ? '<span class="add-column" title="添加列">+</span>' : ''}
                `;
                
                // 右键菜单
                th.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    showColumnActions(e, colIndex);
                });
                
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            
            // 创建表格内容
            for (let rowIndex = 1; rowIndex < tableData.length; rowIndex++) {
                const row = document.createElement('tr');
                row.dataset.row = rowIndex;
                
                tableData[rowIndex].forEach((cell, colIndex) => {
                    const td = document.createElement('td');
                    td.dataset.row = rowIndex;
                    td.dataset.col = colIndex;
                    td.innerHTML = `
                        <div class="cell-editable" contenteditable="true">${escapeHtml(cell)}</div>
                        ${rowIndex === tableData.length - 1 && colIndex === 0 ? '<span class="add-row" title="添加行">+</span>' : ''}
                    `;
                    
                    // 单元格编辑
                    const cellEditable = td.querySelector('.cell-editable');
                    cellEditable.addEventListener('blur', function() {
                        tableData[rowIndex][colIndex] = this.textContent;
                    });
                    
                    row.appendChild(td);
                });
                
                // 右键菜单
                row.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    showRowActions(e, rowIndex);
                });
                
                tbody.appendChild(row);
            }
            
            // 更新表格
            editableTable.innerHTML = '';
            editableTable.appendChild(thead);
            editableTable.appendChild(tbody);
            
            // 添加列按钮事件
            const addColumnBtns = document.querySelectorAll('.add-column');
            addColumnBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    addColBtn.click();
                });
            });
            
            // 添加行按钮事件
            const addRowBtns = document.querySelectorAll('.add-row');
            addRowBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    addRowBtn.click();
                });
            });
        }
        
        // 显示列操作菜单
        function showColumnActions(event, colIndex) {
            // 移除任何已存在的操作菜单
            removeActionMenus();
            
            // 创建列操作菜单
            const colActions = document.createElement('div');
            colActions.className = 'col-actions';
            colActions.innerHTML = `
                <button class="action-btn delete-btn" data-action="delete-col" data-col="${colIndex}">删除列</button>
                <button class="action-btn" data-action="insert-col-before" data-col="${colIndex}">在前插入列</button>
                <button class="action-btn" data-action="insert-col-after" data-col="${colIndex}">在后插入列</button>
            `;
            
            // 定位菜单
            colActions.style.left = `${event.pageX}px`;
            colActions.style.top = `${event.pageY}px`;
            
            // 添加到文档
            document.body.appendChild(colActions);
            
            // 添加事件监听
            colActions.addEventListener('click', function(e) {
                const target = e.target;
                if (target.tagName === 'BUTTON') {
                    const action = target.dataset.action;
                    const col = parseInt(target.dataset.col);
                    
                    switch (action) {
                        case 'delete-col':
                            deleteColumn(col);
                            break;
                        case 'insert-col-before':
                            insertColumn(col);
                            break;
                        case 'insert-col-after':
                            insertColumn(col + 1);
                            break;
                    }
                    
                    removeActionMenus();
                }
            });
            
            // 点击其他地方关闭菜单
            document.addEventListener('click', function closeMenu(e) {
                if (!colActions.contains(e.target)) {
                    removeActionMenus();
                    document.removeEventListener('click', closeMenu);
                }
            });
        }
        
        // 显示行操作菜单
        function showRowActions(event, rowIndex) {
            // 移除任何已存在的操作菜单
            removeActionMenus();
            
            // 创建行操作菜单
            const rowActions = document.createElement('div');
            rowActions.className = 'row-actions';
            rowActions.innerHTML = `
                <button class="action-btn delete-btn" data-action="delete-row" data-row="${rowIndex}">删除行</button>
                <button class="action-btn" data-action="insert-row-before" data-row="${rowIndex}">在上方插入行</button>
                <button class="action-btn" data-action="insert-row-after" data-row="${rowIndex}">在下方插入行</button>
            `;
            
            // 定位菜单
            rowActions.style.left = `${event.pageX}px`;
            rowActions.style.top = `${event.pageY}px`;
            
            // 添加到文档
            document.body.appendChild(rowActions);
            
            // 添加事件监听
            rowActions.addEventListener('click', function(e) {
                const target = e.target;
                if (target.tagName === 'BUTTON') {
                    const action = target.dataset.action;
                    const row = parseInt(target.dataset.row);
                    
                    switch (action) {
                        case 'delete-row':
                            deleteRow(row);
                            break;
                        case 'insert-row-before':
                            insertRow(row);
                            break;
                        case 'insert-row-after':
                            insertRow(row + 1);
                            break;
                    }
                    
                    removeActionMenus();
                }
            });
            
            // 点击其他地方关闭菜单
            document.addEventListener('click', function closeMenu(e) {
                if (!rowActions.contains(e.target)) {
                    removeActionMenus();
                    document.removeEventListener('click', closeMenu);
                }
            });
        }
        
        // 删除列
        function deleteColumn(colIndex) {
            if (tableData[0].length <= 1) {
                showMessage('表格至少需要保留一列', 'error');
                return;
            }
            
            tableData.forEach(row => {
                row.splice(colIndex, 1);
            });
            
            renderTable();
            showMessage('列已删除', 'success');
        }
        
        // 插入列
        function insertColumn(colIndex) {
            tableData.forEach(row => {
                row.splice(colIndex, 0, '');
            });
            
            renderTable();
            showMessage('列已插入', 'success');
        }
        
        // 删除行
        function deleteRow(rowIndex) {
            if (tableData.length <= 1) {
                showMessage('表格至少需要保留一行', 'error');
                return;
            }
            
            tableData.splice(rowIndex, 1);
            
            renderTable();
            showMessage('行已删除', 'success');
        }
        
        // 插入行
        function insertRow(rowIndex) {
            const colCount = tableData[0].length;
            const newRow = Array(colCount).fill('');
            tableData.splice(rowIndex, 0, newRow);
            
            renderTable();
            showMessage('行已插入', 'success');
        }
        
        // 移除操作菜单
        function removeActionMenus() {
            document.querySelectorAll('.row-actions, .col-actions').forEach(menu => {
                menu.remove();
            });
        }
        
        // 显示消息
        function showMessage(text, type) {
            messageEl.textContent = text;
            messageEl.className = `message ${type}`;
            messageEl.style.display = 'block';
            
            setTimeout(() => {
                messageEl.style.display = 'none';
            }, 3000);
        }
        
        // 保存到本地存储
        function saveToLocalStorage() {
            localStorage.setItem('tableEditorData', JSON.stringify(savedTables));
            
            // 同时保存到服务器
            saveToServer();
        }
        
        // 从本地存储加载
        function loadSavedTables() {
            // 先尝试从服务器加载
            loadFromServer();
            
            // 如果服务器加载失败，从本地存储加载
            const savedData = localStorage.getItem('tableEditorData');
            if (savedData) {
                try {
                    savedTables = JSON.parse(savedData);
                } catch (e) {
                    console.error('解析保存的表格数据失败:', e);
                    savedTables = {};
                }
            }
        }
        
        // 保存到服务器
        function saveToServer() {
            fetch('/text2html/table_data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ tables: savedTables })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存到服务器失败');
                }
                return response.json();
            })
            .then(data => {
                console.log('表格数据已保存到服务器', data);
            })
            .catch(error => {
                console.error('保存到服务器错误:', error);
                // 因为已经保存到本地存储，只需要记录错误
            });
        }
        
        // 从服务器加载
        function loadFromServer() {
            fetch('/text2html/table_data')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('从服务器获取表格数据失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.tables) {
                        savedTables = data.tables;
                        
                        // 同步到本地存储
                        localStorage.setItem('tableEditorData', JSON.stringify(savedTables));
                        
                        // 更新表格列表
                        renderSavedTablesList();
                    }
                })
                .catch(error => {
                    console.error('从服务器加载表格数据错误:', error);
                    // 加载失败时会从本地存储加载
                });
        }
        
        // 渲染已保存的表格列表
        function renderSavedTablesList() {
            savedTablesList.innerHTML = '';
            
            const tableNames = Object.keys(savedTables);
            if (tableNames.length === 0) {
                savedTablesList.innerHTML = '<li>暂无保存的表格</li>';
                return;
            }
            
            tableNames.forEach(name => {
                const table = savedTables[name];
                const li = document.createElement('li');
                
                // 格式化时间
                const date = new Date(table.timestamp);
                const formattedDate = `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
                
                li.innerHTML = `
                    <div>
                        <strong>${escapeHtml(name)}</strong>
                        <div><small>保存时间: ${formattedDate}</small></div>
                    </div>
                    <div class="table-actions">
                        <button class="btn btn-secondary load-table-btn" data-name="${escapeHtml(name)}">加载</button>
                        <button class="btn btn-danger delete-table-btn" data-name="${escapeHtml(name)}">删除</button>
                    </div>
                `;
                
                savedTablesList.appendChild(li);
            });
            
            // 添加加载表格事件
            document.querySelectorAll('.load-table-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const tableName = this.dataset.name;
                    loadTable(tableName);
                });
            });
            
            // 添加删除表格事件
            document.querySelectorAll('.delete-table-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const tableName = this.dataset.name;
                    deleteTable(tableName);
                });
            });
        }
        
        // 加载表格
        function loadTable(tableName) {
            if (savedTables[tableName]) {
                tableData = savedTables[tableName].data;
                currentTableName = tableName;
                tableNameInput.value = tableName;
                renderTable();
                showMessage(`表格 "${tableName}" 已加载`, 'success');
            }
        }
        
        // 删除表格
        function deleteTable(tableName) {
            if (confirm(`确定要删除表格 "${tableName}" 吗？`)) {
                delete savedTables[tableName];
                saveToLocalStorage();
                renderSavedTablesList();
                showMessage(`表格 "${tableName}" 已删除`, 'success');
                
                // 如果当前表格被删除，清空当前表格
                if (currentTableName === tableName) {
                    tableData = [['']];
                    currentTableName = '';
                    tableNameInput.value = '';
                    renderTable();
                }
            }
        }
        
        // 工具函数：转义HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // 工具函数：补零
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        
        // 初始化表格
        renderTable();
    </script>
</body>
</html>
